<template>
  <div class="inventory-container">
    <el-row>
      <el-col :span="24" style="padding-top: 0px; padding-left: 24px;">
        <el-form :inline="true" :model="filter" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input v-model="filter.inventoryTitle" placeholder="单据标题" clearable />
          </el-form-item>
          <el-form-item label="单据编号">
            <el-input v-model="filter.inventoryId" placeholder="单据编号" clearable />
          </el-form-item>
          <el-form-item label="往来单位">
            <el-input v-model="filter.targetObjName" placeholder="往来单位" clearable />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="filter.subCommodityName" placeholder="商品名称" clearable />
          </el-form-item>

          <warehouse-select v-model="filter.wareHouse" label="仓库" prop="wareHouse"
            :inventoryUiAction="inventoryUiAction" />
          <el-form-item label="状态">
            <el-select v-model="filter.status" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="待审核" :value="CommonOrderStatus.WaitReview.code" />
              <el-option label="已审核" :value="CommonOrderStatus.Passed.code" />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 300px" label="日期范围">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
        <el-button icon="Plus" @click="createInventory()" type="primary">{{getCreateOrderBtnText}}</el-button>        
        <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
        <el-table v-loading="loading" :data="dataList" style="width: 100%; min-width: 600px; height: 100%;"
          @row-click="handleRowClick">
          <el-table-column label="单据标题" align="center" prop="title" width="180" />
          <el-table-column label="单据编号" align="center" prop="docCode" width="180" />
          <el-table-column label="往来单位" align="center">
            <template #default="scope">
              {{ scope.row.targetObject?.name }}
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center">
            <template #default="scope">
              {{ scope.row.wareHouse?.name }}
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center">
            <template #default="scope">
              {{ scope.row.type?.name }}
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'">
                {{ scope.row.status.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.operateDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-link :underline="false" type="primary" @click.stop="showDetail(scope.row)">
                详情
              </el-link>
              <el-link v-if="scope.row.status.code === CommonOrderStatus.WaitReview.code" :underline="false"
                type="danger" style="margin-left: 12px;" @click.stop="reviewInventory(scope.row)">
                审核
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { CommonOrderStatus, DocType } from '../../public/engine/common/docDefinition'
import { DataPage } from '../../public/network/communicationConverter'
import { InventoryFilter } from '../../public/engine/inventory/inventory'
import { InventoryInOutType } from '../../public/engine/inventory/inventory'
import { WareHouse } from '../../public/engine/inventory/warehouse'
import { Util } from '../../public/utils/util'
import { deleteInventoryNetworkCache } from '../../public/network/api'
import { DateUtil } from '../../public/utils/dateUtil'
import EventBus from '../../public/engine/ipc/eventBus'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'

export default {
  name: 'InventoryMgrPage',

  components: {
    WarehouseSelect
  },

  props: {
    inoutType: {
      type: Number,
      default: InventoryInOutType.In
    }
  },
  data() {
    return {
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      filter: new InventoryFilter(),
      dateRange: [],
      dataList: [],
      inventoryUiAction: new InventoryUiAction(),
      CommonOrderStatus,
      InventoryInOutType
    }
  },
  created() {
    this.$nextTick(() => {
      this.getList()   
  })

    EventBus.on('inventoryUpdated', this.getList)
  },

  computed: { 
    getCreateOrderBtnText() { 
      return this.inoutType === InventoryInOutType.In ? '新建入库单' : '新建出库单'
    },
  },

  methods: {
    async getList() {
      console.log('getList inoutType:', this.inoutType);
      try {
        this.loading = true

        // Update filter with date range
        if (this.dateRange?.length === 2) {

          let date = new Date();
          date.setHours(0, 0, 0, 0);
          date.getFullYear

          this.filter.createStartDate = this.dateRange[0];
          this.filter.createEndDate = new Date(this.dateRange[1])
          this.filter.createEndDate.setHours(23, 59, 59, 999)

        } else {
          this.filter.createStartDate = null
          this.filter.createEndDate = null
        }

        const res = await this.inventoryUiAction.getInventoryData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
          filter: {
            orderType: this.inoutType == InventoryInOutType.In ? DocType.RKD.code : DocType.CKD.code,
            ...this.filter.toJson({ withState: true })
          }
        })

        if (res?.data?.dataList) {
          this.dataList = res.data.dataList
          this.total = res.data.pageInfo?.total || res.data.dataList.length
        } else if (res?.resErr) {
          ElMessage.error('获取出入库单列表失败: ' + res.resErr)
        }
      } catch (error) {
        console.error('获取出入库单列表失败', error)
        ElMessage.error('获取出入库单列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      //console.log("date range: ", this.dateRange);
      this.getList()
    },

    resetSearch() {
      this.filter.clear()
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.getList()
    },

    refreshList() {
      deleteInventoryNetworkCache(); // 删除缓存
      this.getList()
    },

    createInventory() {
      const inOutType = this.inoutType
      this.$router.push({
        path: '/inventory/inventorydoc/inventory',
        query: { inOutType }
      })
    },

    showDetail(row) {
      this.$router.push({
        path: '/inventory/inventorydoc/inventory',
        query: {
          id: row.id,
          inOutType: row.inOutType
        }
      })
    },

    handleRowClick(row) {
      this.showDetail(row)
    },

    async reviewInventory(row) {
      try {
        await ElMessageBox.confirm(
          `确定要审核单据【${row.docCode}】吗?`,
          '审核确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const res = await this.inventoryUiAction.reviewInventory({
          idList: [row.id]
        })

        if (res?.data != null) {
          ElMessage.success('审核成功')
          this.getList()
        } else if (res?.resErr) {
          ElMessage.error('审核失败: ' + res.resErr)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核操作失败')
        }
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      return DateUtil.getDayTitle(dateStr)
    },

    beforeUnmountFromParent() {
      //console.log('inventoryMgrPage: beforeUnmountFromParent')
      EventBus.off('inventoryUpdated', this.getList)
    },
  }
}
</script>

<style scoped>
.inventory-container {
  padding-top: 0px;
  padding-left: 20px;

}
</style>